package com.hcinfos.gsoo.ui;

import java.io.File;
import java.io.FileOutputStream;

import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.DateFormat;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.hcinfos.gsoo.R;
import com.hcinfos.gsoo.config.Common;
import com.hcinfos.gsoo.config.Constants;
import com.hcinfos.gsoo.config.Urls;
import com.hcinfos.gsoo.enity.Coupon;
import com.hcinfos.gsoo.https.HttpClientUtil;
import com.hcinfos.gsoo.interaze.DialogCallBack;
import com.hcinfos.gsoo.util.DialogUtil;
import com.hcinfos.gsoo.util.ImageUtil;
import com.hcinfos.gsoo.util.LogUtil;
import com.hcinfos.gsoo.util.ImageUtil.ImageCallback;

public class CouponDetailActivity extends Activity implements OnClickListener {
	private TextView agreeTv;
	private TextView reg_tv;
	private ImageButton left_ib;
	private TextView center_tv;

	private ImageView detail_img;
	private Context context;
	private TextView couponName;
	private TextView dateName;
	private TextView des;

	private Button down_button;
	private int type = 0;

	private final int VIP_SUCCESS = 0x1120;
	private final int VIP_FAIL = VIP_SUCCESS + 1;
	private final int VIP_NEED_LOGIN = VIP_SUCCESS + 2;
	private final int LOGIN_RESULT_CODE = VIP_SUCCESS + 3;
	private TextView tip;
	private Dialog progressDialog;
	private Activity activity;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		int width = this.getWindowManager().getDefaultDisplay().getWidth();
		Common.PROPORTION = width / 320f;
		Common.WIDTH = width;
		activity = this;
		context = this;
		progressDialog = DialogUtil.createProgressDialog(this, "提示",
				"会员卡领取中...");
		setContentView(R.layout.activity_coupon_detail);
		initRes();
	}

	private void initRes() {
		left_ib = (ImageButton) findViewById(R.id.left_ib);
		reg_tv = (TextView) findViewById(R.id.reg_tv);
		left_ib.setOnClickListener(this);
		reg_tv.setOnClickListener(this);
		reg_tv.setVisibility(View.GONE);
		center_tv = (TextView) findViewById(R.id.center_tv);
		detail_img = (ImageView) findViewById(R.id.detail_img);
		couponName = (TextView) findViewById(R.id.couponName);
		dateName = (TextView) findViewById(R.id.dateName);
		des = (TextView) findViewById(R.id.des);
		down_button = (Button) findViewById(R.id.down_button);
		down_button.setOnClickListener(this);
		tip = (TextView) findViewById(R.id.tip);

	}

	private Coupon coupon;
	private Bitmap bitMap;

	@Override
	protected void onResume() {

		coupon = (Coupon) getIntent().getSerializableExtra("coupon");
		type = getIntent().getIntExtra("type", 0);
		if (type == 0) {
			down_button.setText("下载到手机端");
			center_tv.setText("优惠详情");
		} else {
			down_button.setText("领取会员卡");
			center_tv.setText("会员详情");
		}
		tip.setVisibility(View.GONE);
		if (coupon == null)
			return;
		couponName.setText(coupon.getActName());
		String startTime = coupon.getAddDatetime();
		String endTime = coupon.getEndAddDatetime();
		String desContent = coupon.getActDes();
		if (startTime == null) {
			startTime = "暂无";
		}
		if (endTime == null) {
			endTime = "暂无";
		}
		if (desContent == null) {
			desContent = "暂无";
		}
		dateName.setText("有效期:  " + startTime + " 至 " + endTime);
		des.setText(desContent);
		String url = Constants.SERVER + coupon.getImgAddr()
				+ Constants.IMG_THUMB_512_DIR + coupon.getCouponImg() + ".jpg";
		detail_img.setDrawingCacheEnabled(true);
		ImageUtil.setThumbnailView(url, detail_img, context,
				new ImageCallback() {
					@Override
					public void loadImage(Bitmap bitmap, String imagePath) {
						detail_img.setImageBitmap(bitmap);
					}
				}, true, false);
		super.onResume();
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.left_ib:
			finish();
			break;
		case R.id.down_button:
			if (type == 0) {
				try {
					bitMap = detail_img.getDrawingCache();
					saveBitmapToFile(bitMap);
				} catch (Exception e) {
					Toast.makeText(context, "下载失败", 500).show();
				}
			} else {
				if (progressDialog != null)
					progressDialog.show();
				useVip();
			}
			break;
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (bitMap != null && !bitMap.isRecycled()) {
			bitMap.recycle();
		}
	}

	private void useVip() {

		new Thread(new Runnable() {

			@Override
			public void run() {

				try {
					String result = HttpClientUtil.getFromWebByHttpClient(
							context,
							Urls.USER_VIP_CARD + "record.id=" + coupon.getId());
					LogUtil.d("wxf", "result:" + result);
					if (result == null) {
						Message msg = handler.obtainMessage();
						msg.what = VIP_FAIL;
						handler.sendMessage(msg);
					} else {
						JSONObject obj = new JSONObject(result);
						String message = obj.getString("message");
						int state = obj.getInt("state");
						if (state == 200) {
							Message msg = handler.obtainMessage();
							msg.what = VIP_SUCCESS;
							msg.obj = message;
							handler.sendMessage(msg);
						} else if (state == 198) {
							Message msg = handler.obtainMessage();
							msg.what = VIP_NEED_LOGIN;
							handler.sendMessage(msg);// need login
						} else {
							Message msg = handler.obtainMessage();
							msg.what = VIP_FAIL;
							msg.obj = message;
							handler.sendMessage(msg);
						}
					}

				} catch (Exception e) {
					LogUtil.d("wxf", "useVip:" + e.toString());
					Message msg = handler.obtainMessage();
					msg.what = VIP_FAIL;
					handler.sendMessage(msg);
				}

			}
		}).start();
	}

	Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {
			if (progressDialog != null)
				progressDialog.dismiss();
			switch (msg.what) {
			case VIP_SUCCESS:
				String str = "领取成功";
				if (msg.obj != null) {
					str = msg.obj.toString();
				}
				Toast.makeText(context, str, 500).show();
				break;
			case VIP_FAIL:
				String failStr = "领取失败";
				if (msg.obj != null) {
					failStr = msg.obj.toString();
				}
				Toast.makeText(context, failStr, 500).show();
				break;
			case VIP_NEED_LOGIN:
				DialogUtil.createCallLoginDialog(activity, "请登陆，再领取!",
						new DialogCallBack() {

							@Override
							public void viewClick() {

							}

							@Override
							public void ok() {
								Intent intent = new Intent(
										CouponDetailActivity.this,
										LoginActivity.class);
								intent.putExtra("type", Constants.LOGIN_CODE);
								activity.startActivityForResult(intent,
										LOGIN_RESULT_CODE);
							}

							@Override
							public void init(Object obj) {

							}

							@Override
							public void cancel() {

							}
						}, "登陆", "取消");
				break;
			}
		};
	};

	private void saveBitmapToFile(Bitmap bitmap) throws Exception {
		String path = Constants.DIR + "coupon";
		if (bitmap == null)
			return;
		File fileDir = new File(path);
		if (!fileDir.exists()) {
			fileDir.mkdirs();
		}
		File file = new File(path, DateFormat.format("yyyy_MM_dd_kk_mm_ss",
				System.currentTimeMillis()).toString()
				+ ".png");
		if (file.exists()) {
			file.delete();
		}
		FileOutputStream fos = null;
		if (null != bitmap) {
			fos = new FileOutputStream(file);
			bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
			fos.close();
		}
		tip.setText("注意:本次优惠券保存到sdcard/coupon/" + file.getName());
		tip.setVisibility(View.VISIBLE);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
	}
}
